package com.techblor.library.wechat.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;

/**
 * 小程序 工具类
 *
 * @author zhangceven
 */
@Slf4j
public abstract class WxDecodeUtil {

    /**
     * 编码格式
     */
    private static final String ENCODING = "UTF-8";

    /**
     * 加密算法
     */
    public static final String KEY_ALGORITHM = "AES/CBC/PKCS7Padding";

    /**
     * 解密用户信息
     *
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    public static String decrypt(String sessionKey, String encryptedData, String iv) {
        try {
            byte[] data = Base64.decodeBase64(encryptedData);
            byte[] aseKey = Base64.decodeBase64(sessionKey);
            byte[] ivData = Base64.decodeBase64(iv);
            // 如果密钥不足16位，那么就补足
            int base = 16;
            if (aseKey.length % base != 0) {
                int groups = aseKey.length / base + (aseKey.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(aseKey, 0, temp, 0, aseKey.length);
                aseKey = temp;
            }
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            SecretKeySpec spec = new SecretKeySpec(aseKey, "AES");
            AlgorithmParameters parameters = generateIv(ivData);
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] result = cipher.doFinal(data);
            return new String(result, ENCODING);
        } catch (Exception e) {
//            throw new FinException(e.getMessage(),"500");
            log.error("微信解码失败: {}", e.getMessage());
        }

        return null;
    }

    public static AlgorithmParameters generateIv(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

    /**
     * 校验获取用户信息签名
     *
     * @param sessionKey
     * @param rawData
     * @param signature
     * @return
     */
    public static String validateUserInfo(String sessionKey, String rawData, String signature) {
        try {
            if (DigestUtils.sha1Hex(rawData + sessionKey).equals(signature)) {
                return rawData;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return null;
    }
}
